<template>
  <div class="warpper">
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="Information" name="first">
        <div class="form">
          <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="160px" style="width:85%">
            <el-row :gutter="20">
              <el-col :span="11">
                <el-form-item label="Name" prop="name" style="width:460px">
                  <el-input v-model="formData.name" placeholder="Name" />
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="Favorite Suppliers" prop="suppliers">
                  <el-select v-model="formData.suppliersdata" placeholder="Select Favorite Suppliers" multiple
                    :multiple-limit="mutip" style="width:300px">
                    <el-option v-for="item in suppliers" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="Categorys" prop="category_id">
              <treeselect v-model="formData.category_id" :options="deptOptions" :normalizer="normalizer"
                @input="changeHandler" :props="{ value: 'id', label: 'pathLabel', children: 'children' }"
                placeholder="Select Category" style="width: 300px;">
                <div slot="option-label" slot-scope="{ node }" style="white-space: nowrap; font-size: 14px">
                  {{ node.raw.name ? node.raw.name : '' }}
                </div>
                <div slot="value-label" slot-scope="{ node }">{{ node.raw.pathLabel ? node.raw.pathLabel : '' }}</div>
              </treeselect>
            </el-form-item>

            <el-form-item label="SKU" prop="sku" style="width: 460px;">
              <el-input v-model="formData.sku" placeholder="SKU"></el-input>
            </el-form-item>

            <el-form-item label="Price(S$)" prop="price">
              <el-input-number v-model="formData.price" :min="1" label="Price(S$)"
                style="width:300px"></el-input-number>
            </el-form-item>

            <el-form-item label="Packaging" prop="packaging">
              <el-select v-model="formData.packaging" placeholder="Choose Packaging" style="width:300px">
                <el-option v-for="item in packaging" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="UOM" prop="uom">
              <el-input-number v-model="formData.uom" :min="0"></el-input-number>
              <el-select v-model="formData.uom_sku" placeholder="Choose Uom" style="width: 115px;">
                <el-option v-for="item in uom_sku" :key="item.id" :label="item.name" :value="item.name"
                  style="width: 115px;">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="ROP Point" prop="rop">
              <el-input-number v-model="formData.rop" :min="1" style="width:300px"> </el-input-number>
            </el-form-item>

            <el-form-item label="Status" prop="status">
              <el-select v-model="formData.status" placeholder="Choose status" style="width:300px">
                <el-option v-for="item in status" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="Brand" prop="brand_id">
              <el-select v-model="formData.brand_id" placeholder="Choose brand" style="width:300px">
                <el-option v-for="item in brand" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>

            <!--            <el-form-item label="image" style="margin-bottom: 0px;" prop="image">
              <el-upload ref="uploadAvatar" class="avatar-uploader" action="#" :show-file-list="false"
                :on-change="changeAvatar" :auto-upload="false" :http-request="avatarUpload" name="file">
                <img v-if="formData.image" :src="formData.image" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item> -->


            <el-form-item label="Appendix" style="margin-bottom: 0px;">
              <el-upload ref="uploadAvatar" class="avatar-uploader" :on-preview="handlePreview"
                :on-remove="handleRemove" :before-remove="beforeRemove" :on-exceed="handleExceed"
                :on-success="handleSuccess" action="https://v.ttxcx.net/api/admin/mediasv" :show-file-list="true"
                :file-list="fileList" multiple :limit="5" list-type="picture">
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>


            <el-form-item label="Remark" prop="remark" style="width: 460px;">
              <el-input v-model="formData.remark" placeholder="Remark001"></el-input>
            </el-form-item>

          </el-form>
          <div slot="footer" class="dialog-footer" style="margin-left: 170px;">
            <el-button type="primary" @click="saveHandle('ruleForm')">Submit</el-button>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="Supplier" name="second" :disabled="isNew">
        <supplier :id="id" />
      </el-tab-pane>
      <el-tab-pane label="Inventory" name="five" :disabled="isNew">
        <inventory :id="id" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  import CURD from "@/mixin/CURD";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import supplier from "@/components/productinfo/supplier.vue"
  import inventory from "@/components/productinfo/inventory.vue"
  import {
    store as uploadImg
  } from "@/api/medias";
  import Tinymce from "@/components/Tinymce";
  import {
    update,
    show
  } from "@/api/product";
  import {
    index as cateindex
  } from "@/api/product_category";
  import {
    index as superindex
  } from "@/api/supplier";
  import {
    index as brandindex
  } from "@/api/brand";
  export default {
    name: "productadd",
    components: {
      Tinymce,
      Treeselect,
      supplier,
      inventory
    },
    mixins: [CURD],
    data() {
      return {
        fileList: [],
        rules: [],
        mutip: 3,
        brand: [],
        status: [{
          id: 1,
          name: "Normal",
        }, {
          id: 2,
          name: "Hidden",
        }],
        uom_sku: [{
          id: 1,
          name: "KG",
        }, {
          id: 2,
          name: "G",
        }, {
          id: 3,
          name: "ML",
        }, {
          id: 4,
          name: "L",
        }],
        suppliers: [],
        packaging: [{
          id: 1,
          name: "Bottle",
        }, {
          id: 2,
          name: "Pail",
        }, {
          id: 3,
          name: "Bag",
        }, {
          id: 4,
          name: "Packet",
        }],
        activeName: 'first',
        salesman: [{
          id: 1,
          name: "LiLei",
        }, {
          id: 2,
          name: "Haimei",
        }, {
          id: 3,
          name: "Jack ma",
        }],
        credit_term_type: [{
          id: 1,
          name: "day",
        }, {
          id: 2,
          name: "week",
        }, {
          id: 3,
          name: "month",
        }],
        currency: [{
          id: 1,
          name: "sgd",
        }, {
          id: 2,
          name: "usd",
        }],
        id: null,
        isEdit: false,
        isNew: false,
        formData: {
          uom_sku: "KG",
          name: "",
          status: "Normal",
          sku: "",
          rop: "",
          uom: "",
          suppliers: "",
          price: "",
          brand_id: 1,
          packaging: "Bottle",
          image: "",
          remark: "",
          category_id: null,
          category_name: ""
        },
        module: "product",
        newTitle: "New products",
        editTitle: "Edit product",
        group: [],
        title: '',
        defaultTitle: '',
        deptOptions: [],
        isPaginate: true,
        isUploadFile: false,
        fileReader: new FileReader(),
        isShow: false,
        imageUrl: "",
        categories: [],
        searchForm: {

        },
      };
    },
    async created() {
      this.id = this.$route.query.id

      const {
        data
      } = await superindex(1, 100); // 假设index是一个异步函数
      this.suppliers = data;
      try {
        const {
          data
        } = await cateindex(1, 100); // 假设index是一个异步函数
        this.categories = data;
        // 调用handleTree方法处理数据
        this.deptOptions = this.handleTree(data, "id", "parent_id");

      } catch (error) {
        console.error('Failed to fetch categories:', error);
      }
      try {
        const {
          data
        } = await brandindex(1, 100); // 假设index是一个异步函数
        this.brand = data;
      } catch (error) {
        console.error('Failed to fetch brand:', error);
      }

      if (this.id > 0) {
        this.isEdit = true
        const {
          data
        } = await show(this.id);
        var isbbb = [];
        var issp = data.suppliers;
        if (data.suppliers) {
          issp = issp.split(",");
          for (let is = 0; is < issp.length; is++) {
            isbbb.push(parseInt(issp[is]));
          }
          data.suppliersdata = isbbb;
        }
        if (data.image) {
          this.fileList = JSON.parse(data.image)
        }
        this.formData = data;
      } else {
        this.isNew = true
      }

    },
    methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleSuccess(response, file, fileList) {
        file.url = response.data.url;
        this.fileList = fileList;
        console.log(fileList);
      },
      changeHandler(value) {
        const selectedLabel = this.getCategoryPath(value);
        this.formData.category_name = selectedLabel;
        console.log(selectedLabel, "最终标题");
        this.updateLabel(this.deptOptions, value, selectedLabel);
      },
      updateLabel(categories, id, label) {
        for (let category of categories) {
          if (category.id === id) {
            category.pathLabel = label;
            return;
          }
          if (category.children) {
            this.updateLabel(category.children, id, label);
          }
        }
      },
      getCategoryPath(categoryId) {
        const findCategory = (categories, id) => {
          for (let category of categories) {
            if (category.id === id) {
              return category;
            }
            if (category.children) {
              const foundCategory = findCategory(category.children, id);
              if (foundCategory) {
                return foundCategory;
              }
            }
          }
          return null;
        };

        const category = findCategory(this.deptOptions, categoryId);
        if (category) {
          let path = category.name;
          let parent = category.parent_id;
          while (parent !== null && parent !== undefined) {
            const parentCategory = findCategory(this.deptOptions, parent);
            if (parentCategory) {
              path = parentCategory.name + '/' + path;
              parent = parentCategory.parent_id;
            } else {
              break;
            }
          }
          return path;
        } else {
          return '';
        }

      },
      handleClick(tab, event) {
        console.log(tab, event);
      },
      edit(id) {
        this.$router.push({
          path: '/product/editproduct',
          query: {
            id: id
          }
        })
      },
      onOpen(id) { // 展开
        this.currentOpen = id;
      },
      onClose(id) { // 关闭
        if (this.currentOpen === id) {
          this.currentOpen = null;
        }
      },
      getStatusColor(row) { // 状态颜色
        if (row.status === 'Normal') {
          return 'green-text';
        } else if (row.status === 'Hidden') {
          return 'red-text';
        } else {
          return 'yellow-text';
        }
      },
      normalizer(node) {
        if (node.children && node.children.length === 0) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      handleTree(data, id, parentId, children) {
        let config = {
          id: id || 'id',
          parentId: parentId || 'parentId',
          childrenList: children || 'children'
        };

        var childrenListMap = {};
        var nodeIds = {};
        var tree = [];

        for (let d of data) {
          let parentId = d[config.parentId];
          if (childrenListMap[parentId] == null) {
            childrenListMap[parentId] = [];
          }
          nodeIds[d[config.id]] = d;
          childrenListMap[parentId].push(d);
        }

        for (let d of data) {
          let parentId = d[config.parentId];
          if (nodeIds[parentId] == null) {
            tree.push(d);
          }
        }

        for (let t of tree) {
          adaptToChildrenList(t);
        }

        function adaptToChildrenList(o) {
          if (childrenListMap[o[config.id]] !== null) {
            o[config.childrenList] = childrenListMap[o[config.id]];
          }
          if (o[config.childrenList]) {
            for (let c of o[config.childrenList]) {
              adaptToChildrenList(c);
            }
          }
        }
        return tree;
      },
      adjustOrder(row) {
        row.isEdit = true;
      },
      async saveOrder(row) {
        let data = {
          id: row.id,
          order: row.order,
          action: "order"
        };
        row.isEdit = false;
        let {
          info
        } = await update(data);
        this.fetchData();
      },
      transfromData(data) {
        let result = data.map((item) => {
          item.isEdit = false;
          return item;
        });
        return result;
      },
      saveHandle(form) {
        this.save(form);
      },
      async save(form) {
        console.log(this.fileList, "fileListffffffffffffffffffffffffffffffffff")
        const urls = this.fileList.map(item => item.response.data.url);
        this.formData.image = JSON.stringify((this.fileList))

        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {
              this.formData.suppliers = this.formData.suppliersdata.toString();
              if (this.isEdit) {
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success("Edit successfully");
                setTimeout(() => {
                  this.$router.push({
                    path: '/product/productlist',
                  })
                }, 1000);
              }
              if (this.isNew) {
                let {
                  store
                } = require(`@/api/${this.module}`);
                let info1 = await store(this.formData);
                this.$message.success("Add successfully");
                if (info1.info.id) {
                  setTimeout(() => {
                    this.$router.push({
                      path: '/product/editproduct',
                      query: {
                        id: info1.info.id
                      }
                    })
                  }, 1000);
                }
              }
              this.fetchData();
              this.isEdit = false;
              this.isNew = false;
              this.dialogFormVisible = false;
            } catch (error) {
              let result = error.response.data;
              this.$message.error(result.info);
            }
          } else {
            this.$message.error("Data verification error, please input according to the specified rules");
            return false;
          }
        });
      },

      async changeStatus(row) {
        let tips = "";
        if (row.status) {
          tips = "是否启用该文章?";
        } else {
          tips = "是否禁用该文章?";
        }
        this.$confirm(tips, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(async () => {
            let data = {
              id: row.id,
              status: row.status,
              action: "status"
            };
            let {
              info
            } = await update(data);
            this.$message.success(info);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "Cancelled deletion"
            });
          });
      }

    }
  }
</script>
<style>
  .customWidth {
    width: 80%;
  }
</style>
<style>
  .warpper {
    padding: 30px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }

  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }
</style>